using System;
using System.Linq;
using UnityEngine;

namespace DanielSig.UnityExtensions
{
	
	public static class XCollision
	{
		private const float _CORNER_AREA = 10F;
		
		public static void GetContactArea(this Collision col, ref float area, ref Vector3 averagePoint, ref Vector3 averageNormal)
		{
			ContactPoint[] contacts = col.contacts;
			area = _CORNER_AREA;
			int len = contacts.Length;
			if(len > 2)
			{
				Vector3 point = Vector3.zero;
				Vector3 normal = Vector3.zero;
				
				area = XMesh.GetSurface
				(
					contacts.Select<ContactPoint, Vector3>
					(
						x =>
						{
							point += x.point;
							normal += x.normal;
							return x.point;
						}
					).ToArray()
				);
				
				averagePoint = point / len;
				averageNormal = normal / len;
			}
			else if(len == 2)
			{
				area = contacts[0].point.DistanceTo(contacts[1].point);
				averagePoint = (contacts[0].point + contacts[1].point) * 0.5F;
				averageNormal = (contacts[0].normal + contacts[1].normal) * 0.5F;
			}
			else if(len == 1)
			{
				averagePoint = contacts[0].point;
				averageNormal = contacts[0].normal;
			}
			
			if(area < _CORNER_AREA) area = _CORNER_AREA;
		}
	}
}
